package com.openatc.agent.service.impl;

import com.openatc.agent.service.GenericMsgStrategy;
import com.openatc.agent.utils.RedisTemplateUtil;
import com.openatc.comm.data.MessageData;
import com.openatc.core.model.InnerError;
import com.openatc.core.model.RESTRet;
import com.openatc.core.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

import static com.openatc.core.common.IErrorEnumImplInner.E_110;

/**
 * @author ：zhangwenchao
 * @date ：Created in 2022/7/27 10:57
 * @description：status/currentvolume
 * @modified By：
 * @version: $
 */
@Service(value = "status/currentvolume")
public class StatusCurrentvolume extends GenericMsgStrategy {
    /**
     * 向信号机请求相位参数应答失败
     * @param requestData
     * @param responseData
     * @return
     */

    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    /**
     * 信号机成功应答login请求
     * @param requestData
     * @param responseData
     * @return
     */
    @Override
    public RESTRet successGetProcess(MessageData requestData, RESTRet responseData) {
        MessageData res = (MessageData) responseData.getData();
        // 更新login的缓存
        updateCache(requestData.getAgentid(),res);
        return super.successGetProcess(requestData, responseData);
    }

    /**
     * login应答成功，更新login的缓存状态
     * @param agentid
     * @param res
     */
    private void updateCache(String agentid, MessageData res) {
        String key = "response:status/currentvolume:" + agentid;
        res.setCreatetime(DateUtil.date2esstr(new Date()));
        redisTemplateUtil.setValue(key,gson.toJson(res));
    }

    @Override
    public RESTRet failureGetProcess(MessageData requestData, RESTRet responseData) {
        InnerError innerError = (InnerError) responseData.getData();
        // 上次请求未结束/信号机应答超时，从缓存中获取数据
        if (innerError.getErrorCode().equals(E_110.getErrorCode()) ) {
            return redisTemplateUtil.getCacheData(requestData);
        }

        return super.failureGetProcess(requestData, responseData);
    }
}
